/**
 */
package com.dingpeikeji.quickdeer.core.modules.orders.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alipay.api.RefundFastpayByPlatformNopwdApi;
import com.alipay.model.RefundFastpayByPlatformNopwdReq;
import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.utils.excel.ExportExcel;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.cupons.entity.CuponsInfo;
import com.dingpeikeji.quickdeer.core.modules.cupons.service.TCuponsService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrdersOut;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersOutService;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.payinfo.entity.TPayinfo;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.dingpeikeji.quickdeer.modules.realsche.service.FRealscheService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TDemandsService;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;
import com.google.common.collect.Lists;
import com.tencent.WXPay;
import com.tencent.common.Configure;
import com.tencent.protocol.refund_protocol.RefundReqData;

/**
 * 用户订单管理Controller
 * 
 * @author lh
 * @version 2016-06-15
 */
@Controller
@RequestMapping(value = "${adminPath}/orders/tOrders")
public class TOrdersController extends BaseController {

	@Autowired
	private TOrdersService tOrdersService;
	@Autowired
	private TDemandsService demandsService;
	@Autowired
	private TCuponsService tCuponsService;

	@Autowired
	private TCargotypeService tCargotypeService;

	@Autowired
	private FRealscheService fRealscheService;

	@Autowired
	private TOrdersOutService tOrdersOutService;

	@ModelAttribute
	public TOrders get(@RequestParam(required = false) String id) {
		TOrders entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = tOrdersService.get(id);
		}
		if (entity == null) {
			entity = new TOrders();
		}
		return entity;
	}

	@RequiresPermissions("orders:tOrders:view")
	@RequestMapping(value = { "list", "" })
	public String list(TOrders tOrders, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TOrders> page = tOrdersService.findPage(new Page<TOrders>(request, response), tOrders);
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		for(int i=0;i<page.getList().size();i++){
			TOrders order=page.getList().get(i);
			page.getList().get(i).setEndtime(df.format(new Date(order.getDepartdate().getTime() + order.getBookingdays() * 24 * 60 * 60 * 1000)));
		}
		model.addAttribute("page", page);
		return "modules/orders/tOrdersList";
	}
	
	@RequiresPermissions("orders:bus:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(TOrders tOrders, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "订单数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<TOrders> page = tOrdersService.findPageByProvider(new Page<TOrders>(request, response), tOrders);
    		new ExportExcel("订单数据", TOrders.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出订单数据失败！失败信息："+e.getMessage());
		}
		return "modules/orders/warnOrderList";
    }
	
	@RequiresPermissions("orders:plat:view")
    @RequestMapping(value = "exportall", method=RequestMethod.POST)
    public String exportAllFile(TOrders tOrders, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "订单数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<TOrders> page = tOrdersService.findPage(new Page<TOrders>(request, response), tOrders);
    		ExportExcel dispose = new ExportExcel("订单数据", TOrders.class).setDataList(page.getList()).write(response, fileName).dispose();
    		System.out.println(dispose);
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出订单数据失败！失败信息："+e.getMessage());
		}
		return "modules/orders/allOrderList";
    }

	@RequiresPermissions("orders:bus:view")
	@RequestMapping(value = { "busOrderList", "" })
	public String busOrderlist(TOrders tOrders, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (StringUtils.isEmpty(tOrders.getCreateDateQueryStart())
				&& StringUtils.isEmpty(tOrders.getCreateDateQueryEnd())) {
			tOrders.setCreateDateQueryStart(DateUtils.getDate("yyyy-MM-dd"));
			tOrders.setCreateDateQueryEnd(DateUtils.getDate("yyyy-MM-dd"));
		}
		if (tOrders.getOrderstatus() == null) {
			tOrders.setOrderstatus(TOrders.STATUS_PAY);
		}
		Page<TOrders> page = tOrdersService.findPageByProvider(new Page<TOrders>(request, response), tOrders);
		
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		for(int i=0;i<page.getList().size();i++){
			TOrders order=page.getList().get(i);
			page.getList().get(i).setEndtime(df.format(new Date(order.getDepartdate().getTime() + order.getBookingdays() * 24 * 60 * 60 * 1000)));
		}
		model.addAttribute("tOrders", tOrders);
		model.addAttribute("page", page);

		ArrayList<TCargotype> cartypelist = (ArrayList<TCargotype>) tCargotypeService.findalltypes();
		model.addAttribute("tCargotypeList", cartypelist);
		return "modules/orders/busOrderList";
	}

	@RequiresPermissions("orders:plat:view")
	@RequestMapping(value = { "allOrderList" })
	public String allOrderlist(TOrders tOrders, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (StringUtils.isEmpty(tOrders.getCreateDateQueryStart())
				&& StringUtils.isEmpty(tOrders.getCreateDateQueryEnd())) {
			tOrders.setCreateDateQueryStart(DateUtils.getDate("yyyy-MM-dd"));
			tOrders.setCreateDateQueryEnd(DateUtils.getDate("yyyy-MM-dd"));
		}
		if (tOrders.getOrderstatus() == null) {
			tOrders.setOrderstatus(TOrders.STATUS_PAY);
		}
		//String state=request.getParameter("state");
		Page<TOrders> page = tOrdersService.findPage(new Page<TOrders>(request, response), tOrders);
//		if(state!=null&&state.equals("1")){
//			for(int i=0;i<page.getList().size();i++){
//				if(!page.getList().get(i).getOrdertype().equals("7")){
//					page.getList().remove(i);
//					i--;
//					page.setCount(page.getCount()-1);
//				}
//			}
//		}else{
//			for(int i=0;i<page.getList().size();i++){
//				if(page.getList().get(i).getOrdertype().equals("7")){
//					page.getList().remove(i);
//					i--;
//					page.setCount(page.getCount()-1);
//				}
//			}
//		}
		
		for(int i=0;i<page.getList().size();i++){
			if(page.getList().get(i).getUseCupons().equals("1")){
				CuponsInfo info =tCuponsService.getRecordByOrderId(page.getList().get(i).getOrderid());
				if(info!=null){
					page.getList().get(i).setCuponsPrice(info.getMoney());
				}
			}
		}
		
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		for(int i=0;i<page.getList().size();i++){
			TOrders order=page.getList().get(i);
			page.getList().get(i).setEndtime(df.format(new Date(order.getDepartdate().getTime() + order.getBookingdays() * 24 * 60 * 60 * 1000)));
		}
		model.addAttribute("tOrders", tOrders);
		model.addAttribute("page", page);
		//model.addAttribute("state", state);

		TCargotype tCargo = new TCargotype();
		ArrayList<TCargotype> cartypelist = (ArrayList<TCargotype>) tCargotypeService.findList(tCargo);
		model.addAttribute("tCargotypeList", cartypelist);

		return "modules/orders/allOrderList";
	}
	@RequestMapping(value = { "offlineOrderList" })
	public String offlineOrderlist(TOrders tOrders, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (StringUtils.isEmpty(tOrders.getCreateDateQueryStart())
				&& StringUtils.isEmpty(tOrders.getCreateDateQueryEnd())) {
			tOrders.setCreateDateQueryStart(DateUtils.getDate("yyyy-MM-dd"));
			tOrders.setCreateDateQueryEnd(DateUtils.getDate("yyyy-MM-dd"));
		}
		List<TOrders> list = tOrdersService.findOfflineOrder("1");
		//Page<TOrders> page = tOrdersService.findPage(new Page<TOrders>(request, response), tOrders);
		model.addAttribute("tOrders", list);
		//model.addAttribute("page", page);
		
		return "modules/orders/offlineOrderList";
	}

	@RequiresPermissions("orders:warn:view")
	@RequestMapping(value = { "warnOrderList" })
	public String warnOrderlist(TOrders tOrders, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		Page<TOrders> page = tOrdersService.findWarnList(new Page<TOrders>(request, response), tOrders);
		model.addAttribute("tOrders", tOrders);
		model.addAttribute("page", page);

		TCargotype tCargo = new TCargotype();
		ArrayList<TCargotype> cartypelist = (ArrayList<TCargotype>) tCargotypeService.findList(tCargo);
		model.addAttribute("tCargotypeList", cartypelist);

		return "modules/orders/warnOrderList";
	}

	@RequiresPermissions("orders:bus:view")
	@RequestMapping(value = "busOrdersForm")
	public String busOrdersForm(TOrders tOrders, Model model) {
		String offermount = tOrdersService.findOfferMount(tOrders.getOrderid());
		tOrders.setOffermount(offermount);
		model.addAttribute("tOrders", tOrders);
		return "modules/orders/tOrdersViewByBus";
	}
	//修改订单
	@RequiresPermissions("orders:plat:edit")
	@RequestMapping(value = "editOrder")
	public String editOrder(TOrders orders) {
		tOrdersService.editOrder(orders);
		return "redirect:/a/orders/tOrders/busOrderList";
	}

	@RequiresPermissions("orders:warn:edit")
	@RequestMapping(value = "warnForm")
	public String warnForm(TOrders tOrders, Model model) {
		String orderRemarks = tOrdersService.findOrderRemarks(tOrders.getOrderid());
		tOrders.setOrderRemarks(orderRemarks);
		String offermount = tOrdersService.findOfferMount(tOrders.getOrderid());
		tOrders.setOffermount(offermount);
		model.addAttribute("tOrders", tOrders);
		return "modules/orders/tOrdersWarnForm";
	}

	@RequiresPermissions("orders:plat:view")
	@RequestMapping(value = "form")
	public String form(TOrders tOrders, Model model) {
		model.addAttribute("tOrders", tOrders);
		return "modules/orders/tOrdersForm";
	}

	@RequiresPermissions("orders:plat:edit")
	@RequestMapping(value = "troubleform")
	public String troubleform(TOrders tOrders,HttpServletRequest request, Model model) {
		String t=request.getParameter("t");
		if(t != null &&t.length()>0){
			model.addAttribute("t", t);
		}
		model.addAttribute("tOrders", tOrders);
		return "modules/orders/tOrdersTroubleForm";
	}

	@RequiresPermissions("orders:tOrders:edit")
	@RequestMapping(value = "save")
	public String save(TOrders tOrders, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, tOrders)) {
			return form(tOrders, model);
		}
		tOrdersService.save(tOrders);
		addMessage(redirectAttributes, "保存用户订单管理成功");
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/?repage";
	}

	@RequiresPermissions("orders:plat:edit")
	@RequestMapping(value = "trouble")
	public String trouble(TOrders tOrders, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) {
		tOrdersService.trouble(tOrders);
		addMessage(redirectAttributes, "标记问题订单成功");
		String t=request.getParameter("t");
		if(t != null &&t.length()>0){
			return "redirect:" + Global.getAdminPath() + "/orders/tOrders/busOrderList?repage";
		}
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/allOrderList?repage";
	}
	
	

	@RequiresPermissions("orders:bus:edit")
	@RequestMapping(value = "orderback")
	public String orderback(TOrders tOrders, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request, HttpServletResponse response) {
		tOrders.setOrderstatus(TOrders.STATUS_BACK);
		tOrders.setSettlereason(TOrders.SETTLE_REASON_BUSBACK);

		//tOrdersService.orderback(tOrders);
		// 退款
		doBackMoney(tOrders, redirectAttributes, request, response);
		addMessage(redirectAttributes, "车队退单成功！");
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/busOrderList?repage";
	}

	@RequiresPermissions("orders:tOrders:edit")
	@RequestMapping(value = "confirm")
	public String confirm(TOrders tOrders, Model model, RedirectAttributes redirectAttributes) {
		tOrdersService.confirm(tOrders);
		addMessage(redirectAttributes, "用户订单确认成功");
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/busOrderList?repage";
	}

	@RequiresPermissions("orders:warn:edit")
	@RequestMapping(value = "changebus")
	public String changebus(TOrders tOrders, Model model, RedirectAttributes redirectAttributes) {
		//变更为已取消
		tOrders.setSettlereason(TOrders.SETTLE_REASON_CHGBUS);
		tOrders.setOrderstatus(TOrders.STATUS_BACK);

		tOrdersService.changebus(tOrders);

		addMessage(redirectAttributes, "更换车队成功");
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/warnOrderList?repage";
	}

	@RequiresPermissions("orders:warn:edit")
	@RequestMapping(value = "breakbus")
	public String breakbus(TOrders tOrders, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request, HttpServletResponse response) {
		// 车队违约
		tOrders.setOrderstatus(TOrders.STATUS_BACK);
		tOrders.setSettlereason(TOrders.SETTLE_REASON_BREAK);
		//tOrdersService.breakbus(tOrders);
		// 退款
		doBackMoney(tOrders, redirectAttributes, request, response);
		addMessage(redirectAttributes, "车队违约成功");
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/warnOrderList?repage";
	}

	@RequiresPermissions("orders:warn:edit")
	@RequestMapping(value = "platback")
	public String platback(TOrders tOrders, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request, HttpServletResponse response) {
		tOrders.setOrderstatus(TOrders.STATUS_BACK);
		tOrders.setSettlereason(TOrders.SETTLE_REASON_FLATBACK);

		//tOrdersService.platback(tOrders);
		// 退款
		doBackMoney(tOrders, redirectAttributes, request, response);
		addMessage(redirectAttributes, "车队退单成功！");
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/warnOrderList?repage";
	}

	@RequiresPermissions("orders:tOrders:edit")
	@RequestMapping(value = "delete")
	public String delete(TOrders tOrders, RedirectAttributes redirectAttributes) {
		tOrders = tOrdersService.get(tOrders);
		if (tOrders.getOrderstatus().equals(TOrders.STATUS_CANCEL)
				|| tOrders.getOrderstatus().equals(TOrders.STATUS_PAY)) {
			tOrdersService.delete(tOrders);
			addMessage(redirectAttributes, "删除用户订单管理成功");
		} else {
			addMessage(redirectAttributes, "只有作废或支付过的订单才能删除");
		}
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/?repage";
	}

	@RequestMapping("doBackMoney")
	public void doBackMoney(TOrders orders, RedirectAttributes redirectAttributes, HttpServletRequest request,
			HttpServletResponse response) {
		TOrders torders = fRealscheService.getOrders(orders.getOrderid());
		// ==========>>数据校验
		List<String> messages = Lists.newArrayList(); // 消息
		Integer purchasenum = StringUtils.isEmpty(orders.getPurchasenum()) ? 0
				: Integer.valueOf(orders.getPurchasenum());
		Integer childnum = StringUtils.isEmpty(orders.getChildnum()) ? 0 : Integer.valueOf(orders.getChildnum());
		Integer tpurchasenum = StringUtils.isEmpty(torders.getPurchasenum()) ? 0
				: Integer.valueOf(torders.getPurchasenum());
		Integer tchildnum = StringUtils.isEmpty(torders.getChildnum()) ? 0 : Integer.valueOf(torders.getChildnum());
		if (purchasenum + childnum <= 0) {
			messages.add("退款数量至少为1张！");
		} else if (!(purchasenum <= tpurchasenum && childnum <= tchildnum)) {
			messages.add("退票数量不正确！");
		}
		// ==========>>数据校验<<结束
		boolean sendSms = false; // 是否发送短信
		if (messages.isEmpty()) {
			TPayinfo payinfo = torders.getPayinfo();
			if (payinfo != null && payinfo.getDiscountid() != null) {

				String payway = torders.getPayway();
				// 批次号，必填，格式：当天日期[8位]+序列号[3至24位]，如：201603081000001
				String batch_no = new SimpleDateFormat("yyyyMMdd").format(new Date())
						+ UUID.randomUUID().toString().replace("-", "").substring(0, 16);
				// 退款笔数，必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
				String batch_num = "1";
				Double money = (Double) Double.valueOf(torders.getDueamount());
				// 退款详细数据，必填，格式（支付宝交易号^退款金额^备注），多笔请用#隔开
				String detail_data = payinfo.getFlowno() // 流水号就是支付宝单号
						+ "^" + money + "^" + orders.getPurchasenum() + "," + orders.getChildnum(); // 退款数量
				if (payway.equals(TOrders.PAY_WAY_ALIPAY)) { // 支付宝支付
					String refund_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

					try {
						RefundFastpayByPlatformNopwdReq req = new RefundFastpayByPlatformNopwdReq(batch_no, refund_date,
								batch_num, detail_data);
						new RefundFastpayByPlatformNopwdApi().execute(req, request, response);
						// 保存退款信息
						TOrdersOut orderOut = new TOrdersOut();
						orderOut.setOrderid(Integer.parseInt(orders.getOrderid()));
						orderOut.setBatchNo(batch_no);
						orderOut.setOutnum(Integer.parseInt(orders.getPurchasenum()));
						orderOut.setRtnmoney(money);
						orderOut.setOutchildnum(
								Integer.parseInt(orders.getChildnum() == null ? "0" : orders.getChildnum()));
						orderOut.setNotifyed(TOrdersOut.NOTIFED_NO);
						orderOut.setOutuserid(UserUtils.getUser().getId());
						orderOut.setRtnstatus(TOrdersOut.RTN_STATUS_FAIL);
						tOrdersOutService.save(orderOut);
						fRealscheService.proConfirmSysRtn(orderOut.getOutid(), orders.getSettlereason());
						// return null;
						messages.add("支付宝退票请求成功！");
						sendSms = true;
					} catch (Exception e) {
						messages.add("请求退款异常！");
					}
				}
				if (payway.equals(TOrders.PAY_WAY_WXPAY)) { // 微信支付
					String out_trade_no = "";
					for (int i = 0; i < 32 - orders.getOrderid().length(); i++) { // 补齐32位字符串
						out_trade_no += "0";
					}
					int moneyint = (int) (Double.valueOf(money) * 100);
					out_trade_no += orders.getOrderid();
					RefundReqData refundReqData = new RefundReqData(""// payinfo.getFlowno()
							, out_trade_no, "", batch_no, (int) (Double.valueOf(torders.getDueamount()) * 100),
							moneyint, Configure.getMchid(), "CNY");

						try {
							String responseString = WXPay.requestRefundService(refundReqData);
							// 保存退款信息
							TOrdersOut orderOut = new TOrdersOut();
							orderOut.setOrderid(Integer.parseInt(orders.getOrderid()));
							orderOut.setBatchNo(batch_no);
							orderOut.setOutnum(Integer.parseInt(orders.getPurchasenum()));
							orderOut.setRtnmoney(money);
							orderOut.setOutchildnum(
									Integer.parseInt(orders.getChildnum() == null ? "0" : orders.getChildnum()));
							orderOut.setNotifyed(TOrdersOut.NOTIFED_NO);
							orderOut.setOutuserid(UserUtils.getUser().getId());
							orderOut.setRtnstatus(TOrdersOut.RTN_STATUS_FAIL);
							tOrdersOutService.save(orderOut);
							fRealscheService.proConfirmSysRtn(orderOut.getOutid(), orders.getSettlereason());
							messages.add("微信退票请求成功！");
							sendSms = true;
						} catch (Exception e) {
							messages.add("请求退款异常！");
						}

				}

			} else {
				messages.add("订单暂未生效！");
			}
		}
		// 订车人申请退单成功后，收到平台短信
		if (sendSms) {
			Sms sms = new Sms();
			sms.setMobile(torders.getPayertel());
			sms.setContent("您购买的由"+torders.getOffice().getName()+"车队提供的用车订单（"+torders.getOrderid()+"）已取消，我们将根据预订规则将相应款项在3个工作日内返回您的支付账户。");
			try {
				SmsApi.sendSms(sms);
			} catch (Exception e) {
			}
		}
		addMessage(redirectAttributes, messages.toArray(new String[] {}));
		return;
	}

}
